package com.xiaomaoguai.crs.web.intercepter;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import com.xiaomaoguai.crs.common.constants.Constants;

/**
 * @ FileName: SecurityInterceptor.java
 * @ Author: WeiHui-Z
 * @ Date: 2017/4/18 8:51
 * @ Version: v1.0.0
 */
public class SecurityInterceptor extends HandlerInterceptorAdapter {

    /**
     * 在进入controller之前执行
     *
     * @param request  请求
     * @param response 响应
     * @param handler  前一个拦截
     * @return true or false
     * @throws Exception ex
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (null == user) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            // 未登录
            if (WebUtils.isAjaxRequest(request)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setHeader("sessionstatus", "timeout"); //在响应头设置session状态
            } else {
                PrintWriter out = response.getWriter();
                StringBuilder builder = new StringBuilder();
                builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
                builder.append("alert(\"登录超时，请重新登录!\");");
                builder.append("window.top.location.href=\"");
                builder.append(request.getContextPath());
                builder.append("\"</script>");
                out.print(builder.toString());
                out.close();
            }
            return false;
        }
        return true;
    }

}
